<template>
  <div class="product-type">
    <div class="content">
      <div class="title">/商品类别</div>
      <el-table
        :data="typeData"
        stripe
        border
        >
        <el-table-column
          prop="name"
          label="类型">
        </el-table-column>

        <el-table-column label="图片" prop="pic">
          　　<template slot-scope="scope">
          　　　　<img :src="serverApi+scope.row.pic" width="40" height="40"/>
          　　</template>
        </el-table-column>

        <el-table-column align="right">
          <template slot="header" slot-scope="scope">
            <el-button
              size="mini"
              @click="handleAdd">新增商品类别</el-button>
          </template>
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
    </div>

    <el-dialog title="商品类型" :visible.sync="dialogFormVisible" @close="cancelDialog">
      <el-form :model="form" :rules="rules" ref="typeForm">
        <el-form-item label="类型名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="类型图片" :label-width="formLabelWidth" prop="pic">
          <el-upload
            class="avatar-uploader"
            :action="serverApi+'images'"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.pic" :src="serverApi+form.pic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
  import serverApi from "@/api";
  export default {
    name: 'ProductType',
    data() {
      return {
        //表格
        typeData: [],
        //表单
        form: {
          name: '',
          pic:'',
          id:null,
        },
        dialogFormVisible:false,
        formLabelWidth: '120px',
        serverApi:serverApi,
        rules: {
          name:[{required: true, message: '请输入商品类别名称', trigger: 'blur'}],
          pic:[{required: true, message: '请上传商品类别图片'}],
        },
        headers: {"token":JSON.parse(sessionStorage.getItem("userInfo")).token}
      }
    },
    created() {
      this.getTypeData()
    },
    methods: {
      getTypeData(){
        this.axios.get('/api/product/type',).then((res=>{
          console.log(res);
          if(res.data.errCode==0){
            this.typeData = res.data.result;
          }
        })).catch(error=>{
          console.log(error)
        });
      },
      handleAdd(){
        this.dialogFormVisible = true;
        this.form={
          name: '',
          pic:'',
          id:null
        }
      },
      handleEdit(index, row) {
        let typeJson = {
          name:row.name,
          pic:row.pic,
          id:row.id
        };
        this.dialogFormVisible = true;
        this.form=typeJson;
      },
      beforeAvatarUpload(file) {
        const isFormat = file.type === 'image/jpeg' || 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isFormat) {
          this.$message.error('上传头像图片只能是JPG或者是PNG格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过2MB!');
        }
        return isFormat && isLt2M;
      },
      handleAvatarSuccess(res, file) {
        console.log(res);
        if(res.errorCode==0){
          this.$message.success(res.message);
          let path = res.newPath;
          let newPath = path.replace(/\\/g,"/");
          this.form.pic=newPath;
          console.log(this.form.pic)
        }
      },
      handleDelete(index, row) {
        this.$confirm('此操作将删除该商品分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.axios.post('/api/product/typeRemove',{id:row.id}).then((res=>{
            if(res.data.errCode==9){
              this.$message.error(res.data.message);
            }else if(res.data.errCode==0){
              this.$message.success(res.data.message);
              this.getTypeData()
            }
          })).catch(error=>{
            console.log(error)
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      cancelDialog(){
        this.$refs.typeForm.resetFields();
        this.dialogFormVisible=false;
        this.form = {}
      },
      //提交数据
      submitData(){
        this.$refs.typeForm.validate(valid => {
          if (valid) {
            let optionType = {
              id:this.form.id,
              name:this.form.name,
              pic:this.form.pic.replace(/\\/g,"/"),
              uping:1
            };
            let url = this.form.id==null?'/api/product/typeAdd':'/api/product/typeAlter';
            this.axios.post(url,optionType).then((res=>{
              if(res.data.errCode==0){
                this.$message.success(res.data.message);
                this.getTypeData();
                this.dialogFormVisible = false
              }
            })).catch(error=>{
              console.log(error)
            });
          }
        })
      },
    }
  }
</script>
<style lang="less" scoped>
  .product-type{
    padding: 0 20px;
    .content{
      .title{
        width: 100%;
        height: 60px;
        line-height: 60px;
      }
      .el-table{
        width: 100%;
      }
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border:1px solid #DCDFE6;
    border-radius: 5px;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
